package com.qq.Servlet.Book;

import com.qq.model.Book;
import com.qq.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//center过滤器的注解
@WebServlet("/center/book/index01")
public class BookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("njhiuiduguhu");
        //这里new一个 DBUtil对象进行查询数据库操作
        resp.setContentType("text/html;charset=utf-8");
        //建立连接
        Connection con= DBUtil.getConnection();
        //抛出异常
        try {
            PreparedStatement ps =  con.prepareStatement("select*from book");
            //使用jdbc查询数据集后，需要ResultSet对象来装载查询结果集
            ResultSet rs =  ps.executeQuery();
            //查询的是一个集合
            List<Book> bookList = new ArrayList<>();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String author = rs.getString("author");
               double price = rs.getDouble("price");
               //这里的Book是我们自己定义的
               Book book =   new Book(id,name,author,price);
               bookList.add(book);
                System.out.println(id+name+author+price);
            }
            //向jsp页面传参数
            req.setAttribute("bookList",bookList);
            req.getRequestDispatcher("/WEB-INF/jsp/book/index.jsp").forward(req,resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //输出到页面
        resp.getWriter().write("恭喜你打印成功");

    }
}
